package com.carlosk.kandicar.data;

import java.net.HttpURLConnection;
import java.util.List;

import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;

import com.carlosk.kandicar.component.colog.COLog;
import com.carlosk.kandicar.util.ReferenceUtils;
import com.carlosk.kandicar.util.ValueUtil;

/**
 * 客户端Session处理
 * 
 * @author LiangXiangJu
 * @creationTime 2014-3-24 下午6:20:04
 * @version
 */
public class SessionData extends BaseData {
	private static final String SESSION_ID = "JSESSIONID";

	/**
	 * 获取session
	 * 
	 * @author carlos carlosk@163.com
	 * @version 创建时间：2014年3月23日 下午9:38:23
	 * @return
	 */
	public static String getSession() {
		return ReferenceUtils.getStringByKey(SESSION_ID);
	}
	
	/**
	 * 更新本地session
	 * 
	 * @author carlos carlosk@163.com
	 * @creationTime 2014-3-24 下午6:36:23
	 * @version
	 * @param httpClient
	 * @return
	 */
	public static Boolean updateSession(DefaultHttpClient httpClient) {
		Boolean success = false;
		String session = null;
		List<Cookie> cookies = httpClient.getCookieStore().getCookies();

		if (cookies.isEmpty()) {
			debugLog("-------Cookie NONE---------");
		} else {

			for (Cookie cookie : cookies) {
				String cookieName = cookie.getName();
				if (ValueUtil.isStrEmpty(cookieName)) {
					continue;
				}
				if (SESSION_ID.equals(cookieName.toUpperCase())) {
					success = true;
					session = cookie.getName() + "=" + cookie.getValue();
					debugLog("session = " + session);
					// update session
					debugLog("我更新了cookie,存储到本地:" + session);
					ReferenceUtils.setString(SESSION_ID, session);
				}
			}
		}
		return success;
	}
	
	/**
	 * 更新本地session
	 * 
	 * @author LiangXiangJu
	 * @creationTime 2014-3-24 下午6:36:49
	 * @version
	 * @param conn
	 * @return
	 */
	public static Boolean updateSession(HttpURLConnection conn) {
		Boolean success = false;
		
		// 获取sessionId
		String sessionStr = conn.getHeaderField("Set-Cookie");
		if (ValueUtil.isNotEmpty(sessionStr)) {
			success = true;
			String session = (sessionStr.substring(0,
					sessionStr.indexOf(";")));
			ReferenceUtils.setString(SESSION_ID, session);
		}
		return success;
	}

	/**
	 * 静态方法的debug
	 * 
	 * @author carlos carlosk@163.com
	 * @version 创建时间：2013年9月6日 下午5:58:41
	 */
	public static void debugLog(String msg) {
		COLog.d(SessionData.class.getSimpleName(), msg);
	}
}
